package com.xingongchang.baolebei.fragment;

import java.util.ArrayList;

import org.afinal.simplecache.ACache;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import android.widget.Toast;

import com.external.androidquery.callback.AjaxStatus;
import com.external.maxwin.view.XListView;
import com.iflytek.speech.RecognizerResult;
import com.iflytek.speech.SpeechError;
import com.iflytek.ui.RecognizerDialog;
import com.iflytek.ui.RecognizerDialogListener;
import com.insthub.BeeFramework.fragment.BaseFragment;
import com.insthub.BeeFramework.model.BusinessResponse;
import com.insthub.BeeFramework.view.MyViewGroup;
import com.insthub.BeeFramework.view.ToastView;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;
import com.umeng.analytics.MobclickAgent;
import com.xingongchang.baolebei.BaolebeiManager;
import com.xingongchang.baolebei.R;
import com.xingongchang.baolebei.activity.CategoryActivity;
import com.xingongchang.baolebei.activity.ProductListActivity;
import com.xingongchang.baolebei.adapter.HomeCategoryAdapter;
import com.xingongchang.baolebei.model.ProtocolConst;
import com.xingongchang.baolebei.model.SearchModel;
import com.xingongchang.baolebei.protocol.CATEGORY;
import com.xingongchang.baolebei.protocol.FILTER;

public class CategoryFragment extends BaseFragment implements OnClickListener,
		BusinessResponse, XListView.IXListViewListener
{
	public ArrayList<CATEGORY> categoryList = new ArrayList<CATEGORY>();
	private View view;
	private ImageView search;
	private EditText input;

	private SearchModel searchModel;

	private Button btn[];
	private MyViewGroup layout;

	private XListView parentListView;

	HomeCategoryAdapter parentListAdapter;
	ACache aCache;
	NetworkInfo mNetworkInfo;// 判断网络是否连接
	boolean istrue;
	DisplayImageOptions options;
	ConnectivityManager mConnectivityManager;

	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		options = new DisplayImageOptions.Builder()
				.showImageOnLoading(R.drawable.default_image)
				.showImageForEmptyUri(R.drawable.default_image)
				.showImageOnFail(R.drawable.default_image).cacheInMemory(true)
				.cacheOnDisk(true).considerExifParams(true)
				.displayer(new RoundedBitmapDisplayer(20)).build();
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState)
	{
		view = inflater.inflate(R.layout.search_category, null);
		// 缓存
		aCache = ACache.get(getActivity());
		// 判断是否连接网络
		mConnectivityManager = (ConnectivityManager) getActivity()
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
		input = (EditText) view.findViewById(R.id.search_input);
		search = (ImageView) view.findViewById(R.id.top_view_search);
		layout = (MyViewGroup) view.findViewById(R.id.search_layout);
		parentListView = (XListView) view.findViewById(R.id.parent_list);
		parentListView.setPullLoadEnable(false);// 有加载
		parentListView.setXListViewListener(this, 1);
		parentListView.setPullRefreshEnable(true);// 无加载更多
		search.setOnClickListener(this);
		searchModel = new SearchModel(getActivity());
		if (mConnectivityManager.getActiveNetworkInfo() != null
				&& mConnectivityManager.getActiveNetworkInfo().isConnected())
		{
			if (mNetworkInfo.getType() == ConnectivityManager.TYPE_WIFI
					|| mNetworkInfo.getType() == ConnectivityManager.TYPE_MOBILE)
			{
				searchModel.searchCategory();
				searchModel.addResponseListener(this);
				addKeywords();
				input.setOnEditorActionListener(new OnEditorActionListener()
				{

					@Override
					public boolean onEditorAction(TextView v, int actionId,
							KeyEvent event)
					{

						if (actionId == EditorInfo.IME_ACTION_SEARCH)
						{
							try
							{
								Intent intent = new Intent(getActivity(),
										ProductListActivity.class);
								FILTER filter = new FILTER();
								filter.keywords = input.getText().toString()
										.toString();
								intent.putExtra(ProductListActivity.FILTER,
										filter.toJson().toString());
								startActivity(intent);
								getActivity().overridePendingTransition(
										R.anim.push_right_in,
										R.anim.push_right_out);

							} catch (JSONException e)
							{
								e.printStackTrace();
							}
						}
						return false;
					}
				});

				parentListAdapter = new HomeCategoryAdapter(getActivity(),
						searchModel.categoryArrayList, options);
				parentListView.setAdapter(parentListAdapter);
				parentListView
						.setOnItemClickListener(new AdapterView.OnItemClickListener()
						{
							@Override
							public void onItemClick(AdapterView<?> parent,
									View view, int position, long id)
							{

								if (position - 1 < searchModel.categoryArrayList
										.size())
								{
									CATEGORY category = searchModel.categoryArrayList
											.get(position - 1);
									try
									{
										Intent it = new Intent(getActivity(),
												ProductListActivity.class);
										FILTER filter = new FILTER();
										filter.category_id = String
												.valueOf(searchModel.categoryArrayList
														.get(position - 1).id);
										it.putExtra(ProductListActivity.FILTER,
												filter.toJson().toString());
										it.putExtra("name",
												searchModel.categoryArrayList
														.get(position - 1).name);
										getActivity().startActivity(it);
										getActivity()
												.overridePendingTransition(
														R.anim.push_right_in,
														R.anim.push_right_out);

									} catch (JSONException e)
									{
										e.printStackTrace();
									}

								}

							}
						});
			}
		}
		CasheFragment();
		return view;
	}

	// 没有网络的情况下
	public void CasheFragment()
	{
		if (mConnectivityManager.getActiveNetworkInfo() == null)
		{
			istrue = true;
			JSONArray categoryJSONArray = aCache.getAsJSONArray("categorys");
			if (null != categoryJSONArray && categoryJSONArray.length() > 0)
			{
				for (int i = 0; i < categoryJSONArray.length(); i++)
				{
					JSONObject categoryObject;
					try
					{
						categoryObject = categoryJSONArray.getJSONObject(i);
						CATEGORY category = CATEGORY.fromJson(categoryObject);
						categoryList.add(category);
					} catch (JSONException e)
					{
						e.printStackTrace();
					}
				}
			}
			if (categoryList.size() != 0)
			{
				if (parentListAdapter == null)
				{
					parentListAdapter = new HomeCategoryAdapter(getActivity(),
							categoryList, options);
					parentListView.setAdapter(parentListAdapter);
				} else
				{
					parentListAdapter.notifyDataSetChanged();
				}

				parentListView
						.setOnItemClickListener(new AdapterView.OnItemClickListener()
						{
							@Override
							public void onItemClick(AdapterView<?> parent,
									View view, int position, long id)
							{
								if (position - 1 < categoryList.size())
								{
									CATEGORY category = categoryList
											.get(position - 1);
									try
									{
										Intent it = new Intent(getActivity(),
												ProductListActivity.class);
										FILTER filter = new FILTER();
										filter.category_id = String
												.valueOf(categoryList
														.get(position - 1).id);
										it.putExtra(ProductListActivity.FILTER,
												filter.toJson().toString());
										it.putExtra(
												"name",
												categoryList.get(position - 1).name);
										getActivity().startActivity(it);
										getActivity()
												.overridePendingTransition(
														R.anim.push_right_in,
														R.anim.push_right_out);

									} catch (JSONException e)
									{
										e.printStackTrace();
									}

								}
							}

						});
			}
		}
	}

	@Override
	public void onClick(View v)
	{

		switch (v.getId())
		{
		case R.id.top_view_search:
			try
			{
				Intent intent = new Intent(getActivity(),
						ProductListActivity.class);
				FILTER filter = new FILTER();
				filter.keywords = input.getText().toString().toString();
				intent.putExtra(ProductListActivity.FILTER, filter.toJson()
						.toString());
				intent.putExtra("name", input.getText().toString());
				startActivity(intent);
				getActivity().overridePendingTransition(R.anim.push_right_in,
						R.anim.push_right_out);

			} catch (JSONException e)
			{

			}
			break;
		}

	}

	// 动态添加button，并设置监听
	public void addKeywords()
	{

		if (searchModel.list.size() > 0)
		{

			layout.removeAllViews();
			btn = new Button[searchModel.list.size()];
			for (int i = 0; i < searchModel.list.size(); i++)
			{
				View view = LayoutInflater.from(getActivity()).inflate(
						R.layout.button_view, null);
				btn[i] = (Button) view.findViewById(R.id.search_keyword);
				btn[i].setText(searchModel.list.get(i).toString());
				layout.addView(view);
			}

			for (int k = 0; k < searchModel.list.size(); k++)
			{
				btn[k].setTag(k);
				btn[k].setOnClickListener(new OnClickListener()
				{
					@Override
					public void onClick(View v)
					{

						int a = (Integer) v.getTag();
						try
						{
							Intent intent = new Intent(getActivity(),
									ProductListActivity.class);
							FILTER filter = new FILTER();
							filter.keywords = btn[a].getText().toString();
							intent.putExtra(ProductListActivity.FILTER, filter
									.toJson().toString());
							startActivity(intent);
							getActivity()
									.overridePendingTransition(
											R.anim.push_right_in,
											R.anim.push_right_out);
						} catch (JSONException e)
						{

						}

					}
				});
			}
		}

	}

	public void showRecognizerDialog()
	{

		RecognizerDialog recognizerDialog = new RecognizerDialog(getActivity(),
				"appid=" + BaolebeiManager.getXunFeiCode());

		recognizerDialog.setEngine("sms", null, null);
		recognizerDialog.setListener(new RecognizerDialogListener()
		{
			@Override
			public void onResults(ArrayList<RecognizerResult> results,
					boolean arg1)
			{
				StringBuffer result = new StringBuffer();
				for (RecognizerResult r : results)
				{
					result.append(r.text);
				}
				if (result.length() > 0)
				{
					input.setText(result.toString().substring(0,
							result.toString().length() - 1));
				}

			}

			@Override
			public void onEnd(SpeechError arg0)
			{
				if (input.getText().toString().equals(""))
				{

					// Toast.makeText(getActivity(), you_not_speak, 0).show();
					ToastView toast = new ToastView(getActivity(),
							getString(R.string.you_did_not_speak));
					toast.setGravity(Gravity.CENTER, 0, 0);
					toast.show();
				} else
				{
					try
					{
						Intent intent = new Intent(getActivity(),
								ProductListActivity.class);
						FILTER filter = new FILTER();
						filter.keywords = input.getText().toString();
						intent.putExtra(ProductListActivity.FILTER, filter
								.toJson().toString());
						startActivity(intent);
						getActivity().overridePendingTransition(
								R.anim.push_right_in, R.anim.push_right_out);
					} catch (JSONException e)
					{

					}
				}

			}
		});
		recognizerDialog.show();

	}

	public void OnMessageResponse(String url, JSONObject jo, AjaxStatus status)
	{
		if (url.endsWith(ProtocolConst.SEARCHKEYWORDS))
		{
			addKeywords();
		} else if (url.endsWith(ProtocolConst.CATEGORY))
		{
			parentListView.stopRefresh();
			parentListView.stopLoadMore();
			parentListView.setRefreshTime();
			parentListAdapter.notifyDataSetChanged();
		}
	}

	@Override
	public void onDestroy()
	{
		super.onDestroy();
		searchModel.removeResponseListener(this);
	}

	@Override
	public void onResume()
	{
		super.onResume();
		MobclickAgent.onPageStart("Search");
		mConnectivityManager = (ConnectivityManager) getActivity()
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
		if (mNetworkInfo != null && mNetworkInfo.isConnected())
		{
			if (mNetworkInfo.getType() == ConnectivityManager.TYPE_WIFI
					|| mNetworkInfo.getType() == ConnectivityManager.TYPE_MOBILE)
			{
				searchModel.searchCategory();
			}
		}
	}

	@Override
	public void onPause()
	{
		super.onPause();
		MobclickAgent.onPageEnd("Search");
	}

	@Override
	public void onRefresh(int id)
	{
		mConnectivityManager = (ConnectivityManager) getActivity()
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
		if (mNetworkInfo != null && mNetworkInfo.isConnected())
		{
			if (mNetworkInfo.getType() == ConnectivityManager.TYPE_WIFI
					|| mNetworkInfo.getType() == ConnectivityManager.TYPE_MOBILE)
			{
				searchModel.searchCategory();
			}
		}

	}

	@Override
	public void onLoadMore(int id)
	{
	}
}
